﻿function $$(obj) {
    return document.getElementById(obj);
}
//获取视口的高度和宽度。 	  
function windowHeight() {
    var de = document.documentElement;
    return self.innerHeight || (de && de.clientHeight) || document.body.clientHeight;
}
function windowWidth() {
    var de = document.documentElement;
    return self.innerWidth || (de && de.clientWidth) || document.body.clientWidth;
}
function parentWindowHeight() {
    var de = parent.document.documentElement;
    return self.innerHeight || (de && de.clientHeight) || parent.document.body.clientHeight;
}
function setWindowSize() {
    var wh = windowHeight();
    var ww = windowWidth();
    //版本1
//    document.getElementById("partArea").style.height = (wh - 78) + "px";
//    document.getElementById("navBar").style.height = (wh - 121) + "px";
//    document.getElementById("frap").style.height = (wh - 121) + "px";
//    document.getElementById("pageFooter").style.width = ww + "px";
//    document.getElementById("mainArea").style.height = (wh - 121) + "px";
//    document.getElementById("mainArea").style.width = (ww - 210) + "px";
//    if (document.getElementById("contentArea") != null) {
//        document.getElementById("contentArea").style.width = (ww - 210) + "px";
//        document.getElementById("contentArea").style.height = (wh - 166) + "px";
//        if (document.getElementById("printArea") != null)
//            document.getElementById("printArea").style.height = document.getElementById("contentArea").scrollHeight - 60 + "px";
//    }
//    if (document.getElementById("MDI_Forms") != null) {
//        document.getElementById("MDI_Forms").style.width = (ww - 210) + "px";
//        document.getElementById("MDI_Forms").style.height = (wh - 156) + "px";
//        if (document.getElementById("printArea") != null)
//            document.getElementById("printArea").style.height = document.getElementById("MDI_Forms").scrollHeight - 60 + "px";
//    }
     
    //版本2
        document.getElementById("partArea").style.height = (wh - 81) + "px";
        document.getElementById("navBar").style.height = (wh - 121) + "px";
        document.getElementById("frap").style.height = (wh - 121) + "px";
        document.getElementById("pageFooter").style.width = ww + "px";
        document.getElementById("mainArea").style.height = (wh - 121) + "px";
        document.getElementById("mainArea").style.width = (ww - 210) + "px";
        if (document.getElementById("contentArea") != null) {
            document.getElementById("contentArea").style.width = (ww - 210) + "px";
            //document.getElementById("contentArea").style.height = (wh - 166) + "px";
            //if (document.getElementById("printArea") != null)
             //   document.getElementById("printArea").style.height = document.getElementById("contentArea").scrollHeight - 60 + "px";
        }
        if (document.getElementById("MDI_Forms") != null) {
            document.getElementById("MDI_Forms").style.width = (ww - 210) + "px";
            //document.getElementById("MDI_Forms").style.height = (wh - 156) + "px";
            //if (document.getElementById("printArea") != null)
             //   document.getElementById("printArea").style.height = document.getElementById("MDI_Forms").scrollHeight - 60 + "px";
        }
}



function setTableHeight(offsetHeight) {
    $("#contentArea").css("overflow", "hidden");
    var TH,
	TH = $(document).height() - offsetHeight;
    $("#tableScroll").height(TH);
    $("#tableScroll").css("overflow", "scroll");
}


function moveBtn(n) {
    var wh = windowHeight();
    var ww = windowWidth();

    if ($("#navBar").css("display") != "none") {
        $("#navBar").css("display", "none");
        $("#mainArea").css("width", (ww - 10) + "px");
        $("#contentArea").css("width", (ww - 10) + "px");
        $("#moveBtn").css("background", "url(../images/show.gif)");
        $('#MDI_Forms').css("width", (ww - 10) + 'px');
    }
    else {
        $("#navBar").css("display", "");
        $("#mainArea").css("width", (ww - 210) + "px");
        $("#contentArea").css("width", (ww - 210) + "px");
        $("#moveBtn").css("background", "url(../images/frap.gif)");
        $('#MDI_Forms').css("width", (ww - 210) + 'px');
    }
}

function OpenDetail(url, title, width, height) {
    window.open(url, title, 'height='+height+', width='+width+', toolbar=no, menubar=no, resizable=yes,location=no, status=no, scrollbars=yes');
}

function GetSelectId() {
    return GetDataGridSelectId('default1')[0];
}

function RemoveSelectRow() {
    var ctls = document.getElementsByName("default1_record");
    var ctl = null;
    for (var i = 0; i < ctls.length; i++) {
        if (ctls[i].checked) {
            ctl = ctls[i];
            break;
        }
    }
    if (ctl == null) return;
    var tr = ctl.parentNode.parentNode;
    tr.parentNode.removeChild(tr);
}



//波神表格JavaScript开始
var tableThColors = new Array();
tableThColors[0] = '#b7e1f6';
tableThColors[1] = '#b2d871';
tableThColors[2] = '#20b4e2';
tableThColors[3] = '#6666cc';
tableThColors[4] = '#33cccc';

var left_table_w = 0; //左侧表格宽度
var scroll_w = 0;
function setScrollTableSize(groupCount, groupEndIndexs) {
    var groupsWidths = new Array();
    for (var i = 0; i < groupCount; i++) {
        groupsWidths[i] = 0;
    }

    var colorArr = new Array();
    var color_row_w = ''; //色块宽度
    var total_color_w = 0; //
 
    var ww = windowWidth();
    var wh = windowHeight();
        document.getElementById("wrap_table").style.width = ww - 30 + "px"; //高度适应，微调

    document.getElementById("wrap_table").style.height = wh -140+ "px"; //高度适应，微调
    document.getElementById("right_table").style.height = document.getElementById("left_table").style.height = wh - 160 + "px"; //高度适应，微调
    var maxH = 0;
    var maxW = 0;

    $('td', $('#right_table_head tr:first')).each(function(i, o) {
        maxW = Math.max($(o).width(), $('#right_table tr:first td').eq(i).width());
        $('div', $(o)).width(maxW);
        $('div', $('#right_table tr:first td').eq(i)).width(maxW);
    });
    $('td', $('#left_table_head tr:first')).each(function(i, o) {
        maxW = Math.max($(o).width(), $('#left_table tr:first td').eq(i).width());
        $(o).width("10%");
        $('#left_table tr:first td').eq(i).width("10%");
        left_table_w += maxW + 5;
    });

    $('td:first', ('.tableStyle tr:first')).width($('#left_table tr:first').width()-7);
    $('td:first', $('#left_table tr')).each(function(i, o) {
        maxH = Math.max($(o).height(), $('td:first', ('#right_table tr')).eq(i).height());
        $(o).height(maxH);
        $('td:first', ('#right_table tr')).eq(i).height(maxH);
    });
    $('td:first', $('#left_table_head tr')).each(function(i, o) {
        maxH = Math.max($(o).height(), $('td:first', ('#right_table_head tr')).eq(i).height());
        $(o).height(maxH);
        $('td:first', ('#right_table_head tr')).eq(i).height(maxH);
    });

    color_row_w = ($('td:last', $('#tableStyle tr:first')).width()) + 4;

    $('td', $('#right_table_head tr')).each(function(cell, o) {
        $('td', $('#right_table tr:first')).eq(cell).width($(o).width());
        var cellGroupIndex = 0;
        for (var i = 0; i < groupCount; i++) {
            if (groupEndIndexs[i] < cell) cellGroupIndex = i;
        }

        groupsWidths[cellGroupIndex] += $(o).width() + 5;
        $(o).css('backgroundColor', tableThColors[cellGroupIndex]);

    });

    var groupBFB = new Array();
    var barTotalWidth = $("#ggTotalWidth").width()+groupsWidths.length;
    //alert(barTotalWidth);
    var groupTotalWidth = 0;
    for (var i = 0; i < groupsWidths.length; i++)
        groupTotalWidth += groupsWidths[i];
    for (var i = 0; i < groupsWidths.length; i++) {
        groupBFB[i] = groupsWidths[i] / groupTotalWidth;
        $("#gg" + i).width(barTotalWidth * groupBFB[i]);
    }
    left_table_w = $('#left_table tr:first').width();
    document.getElementById('move').style.left = left_table_w; //初始化指针位置
    //alert(left_table_w);
    $('#loading').hide();
    $('#wrap_table').css('visibility', 'visible');
    $("#right_table").scroll(function() {

        document.getElementById("left_table").scrollTop = document.getElementById('right_table').scrollTop;
        document.getElementById("right_table_head").scrollLeft = document.getElementById('right_table').scrollLeft;
        var sbLeft = document.getElementById('right_table').scrollLeft;
        var a = ($('tr:first', $('#right_table_head')).width() - scroll_w);
        document.getElementById('move').style.left = parseInt(sbLeft / a * (barTotalWidth - 8) + left_table_w + 1);
    });
}

function moveToColumn(colIndex) {
    var scrollPos = 0;
    $('td', $('#right_table tr:first')).each(function(i, o) {
        scrollPos += $(o).width();
        if (i == colIndex) $('#right_table').animate({ scrollLeft: scrollPos - 32 + 'px' }, 500);
    });
}
//波神表格JavaScript结束




//var str = 'NotNull|Number|Date|Max:2|Min:4';
function strToJson(str) {
    var validArr = str.split('|');
    var arrLen = validArr.length;
    var json = '';
    var sign = '';
    for (var i = 0; i < arrLen; i++) {
        if (validArr[i] == 'NotNull') {
            json += sign + '"NotNull":true';
        }
        if (validArr[i] == 'Number') {
            json += sign + '"Number":true';
        }
        if (/Max/.test(validArr[i])) {
            json += sign + '"Max":' + validArr[i].split(':')[1];
        }
        if (/Min/.test(validArr[i])) {
            json += sign + '"Min":' + validArr[i].split(':')[1];
        }
        sign = ',';
    }
    return '{' + json + '}';
}
//eval('var valid=' + strToJson(s));




function setMDIWindow() {
    //版本1
    //    document.getElementById('contentArea').style.height = (parentWindowHeight() - 202) + 'px';
    //版本2
    document.getElementById('contentArea').style.height = (parentWindowHeight() - 196) + 'px';
}



Array.prototype.inArray = function(value) {
    var arrLen = this.length;
    for (var i = 0; i < arrLen; i++) {
        if (this[i] === value) {
            return true;
        }
    }
    return false;
}

Array.prototype.removeElement = function(value,all) {//删除数组元素,返回元素索引
    var arrLen = this.length;
    for (var i = 0; i < arrLen; i++) {
        if (this[i] === value) {
            this.splice(i, 1);
            if(!all)return i;
        }
    }
}


/********************************
参数说明：
caption(String):标签页名称
url(String):标签页链接
mode(Boolean):是否允许重复打开多个标签页
menuPath(String):用于左侧目录树状态记录（li的ID）
*********************************/
var labelQueue = new Array();
var urlQueue = new Array();
var stateQueue = new Array();
var oIframe = {};
function openIframe(caption, url, mode, menuPath, needBack) {
    if (labelQueue.length > 19) {
        alert("当前打开的标签页数已超出系统允许上限，请先关闭部分标签页后，再进行此操作。");
        return;
    }
    if (labelQueue.length > 14) {
        if (!window.confirm('当前打开的标签页已达' + (labelQueue.length) + '个，可能影响系统运行性能，您确定要继续打开新的标签页吗？\n\n点击“确定”继续，点击“取消”终止操作。\n\n建议您先将部分标签页关闭后，再继续打开新的标签页。')) {
            return;
        }
    }

    var iframeId = createIdForIframe(); //
    /*****************************/
    if (needBack) {
        var oLi = $('#iframeLabel', parent.document).find('li[class=currentTagNav]');
        (eval('oIframe.' + iframeId + '_prev="' + oLi.attr('id') + '"')); //记录来源
        //alert('oIframe.' + iframeId + '_prev="' + oLi.attr('id') + '"');
    }
    /*****************************/
    if (mode) {
        createTag(caption, url, iframeId, menuPath);
        return iframeId;
    }
    else {
        var createNew = true;
        for (var i = 0; i < urlQueue.length; i++) {
            if (urlQueue[i] == url) {
                window.frames[labelQueue[i]].location.href = urlQueue[i];//刷新已经打开标签页。
                if ($('#li_' + labelQueue[i]).attr('class') == 'otherTagNav') {
                    $('#li_' + labelQueue[i]).trigger('click');
                    return labelQueue[i]; //junp
                }
                createNew = false;
                break;
            }
        }
        if (createNew||urlQueue.length==0) createTag(caption, url, iframeId, menuPath);
    }
    expNav(menuPath);//左边状态驻留
    function createTag(caption, url, id, menuPath) {
        showLoading();
        //$('#mainArea').block({ message: '<img src="/images/iframe_loading.gif" alt="" />&nbsp;&nbsp;页面加载中，请稍后......', css: { background: 'transparent', border: '0px solid #a00' }, overlayCSS: { backgroundColor: 'transparent', opacity: '0' }, fadeIn: 0});
        $('#MDI_Forms div').css('display', 'none');
        $('#iframeLabel li').removeClass('currentTagNav').addClass('otherTagNav');
        $('#iframeLabel li:first').addClass('tagHome').removeClass('otherTagNav').removeClass('currentTagHome'); //处理“我的桌面”
        
        $('#iframeLabel').append('<li menuPath="' + menuPath + '" onclick="activeCurrentIframe(this,\'' + id + '\',\'' + menuPath + '\');" id="li_' + id + '" class="currentTagNav" title="' + caption + '"><a href="#" onclick="colseIframe(\'' + id + '\',\'' + url + '\',' + mode + ',\'' + menuPath + '\');return false;" title="关闭选项卡"></a><span>' + caption + '</span></li>');

        $('#MDI_Forms').append('<div id="div_' + id + '"><iframe name="' + id + '" id="' + id + '" src="' + url + '" scrolling="no" frameborder="0" width="100%" height="100%"></iframe></div>');
        labelQueue.push(id); //将iframeID加入队列
        urlQueue.push(url); //将路径加入队列
        stateQueue.push(id);
        showCurrentLabel(1, null);
    }
    if (createNew) { return iframeId; }
}


function activeCurrentIframe(obj, id, menuPath) {
    expNav(menuPath);
    
    if ($('#li_' + id).attr('class') != 'otherTagNav') return;
    $('li', $(obj).parent()).removeClass('currentTagNav').addClass('otherTagNav');
    $('li:first', $(obj).parent()).removeClass('otherTagNav').removeClass('currentTagHome').addClass('tagHome'); //处理“我的桌面”
    $(obj).addClass('currentTagNav').removeClass('otherTagNav'); //激活当前label
    $('#MDI_Forms div').css('display', 'none');
    $('#div_' + id).css('display', 'block'); //激活当前iframe
    stateQueue.removeElement(id,true);
    stateQueue.push(id); //将当前激活单元入队
    return id;
}

function colseIframe(id, url, mode) {        //alert('a');
    var oLi = $('#iframeLabel', parent.document).find('li[class=currentTagNav]');
    var tempPrevUrl = $('#' + oLi.attr('id').substring(3)).attr('src');

    showCurrentLabel(2, id);
    hideLoading();//标签页出错时关闭页面隐藏loading
    stateQueue.pop();
    urlQueue.splice(labelQueue.removeElement(id,false),1);
    $('#li_' + id).remove();
    $('#div_' + id).remove();
    if ( stateQueue.length > 0) {
        var currentId = stateQueue[stateQueue.length - 1];
        $('#li_' + currentId).addClass('currentTagNav').removeClass('otherTagNav'); //激活当前label
        //alert($('#li_' + currentId).attr('menuPath'));
        $('#div_' + currentId).css('display', 'block');    //激活当前iframe
        expNav($('#li_' + currentId).attr('menuPath')); //左边状态驻留
    }
    if(labelQueue.length==0) {
        $('#iframeLabel li:first').removeClass('otherTagNav').addClass('currentTagHome');
        $('#MDI_Forms div:first').css('display', 'block');
        if ($(".hasNextNav") != null)
            eachBar($(".hasNextNav").children("ul"));
        secondBar($(".secondNav"));
        $('#slideToggleNav li').removeClass('currentNav');
        //$('#iframeLabel li:first').addClass('tagHome currentTagNav');
    }

    function GetparamUrl(url, item) {
        var sValue = url.match(new RegExp("[\?\&]" + item + "=([^\&]*)(\&?)", "i"))
        return sValue ? sValue[1] : sValue;
    }

    var prevLiId = eval('oIframe.' + id + '_prev');
    if (prevLiId != undefined) {
        var i = 0;
        //alert($('#' + oLi.attr('id').substring(3)).attr('src'));
        var temUrl = GetparamUrl(tempPrevUrl, "urlBack");

        var methodUrl = url.split('|||');
        while (methodUrl.length < 2 && i < 10) {
            temUrl = decodeURIComponent(temUrl);
            methodUrl = temUrl.split('|||');
            i++;
        }

        if (methodUrl.length > 1) {

            //showLoading();
            $('#' + prevLiId.substring(3)).parent().block({ message: '<img src="/images/iframe_loading.gif" alt="" />&nbsp;&nbsp;数据处理中，请稍后......',
                css: { background: 'white', border: '0px solid #a00' },
                overlayCSS: { backgroundColor: '#000000', opacity: '0.3' }, fadeIn: 0
            }); //loading......
            //处理原始URL
        
            var paramUrl = methodUrl[1].split('~~');

            if (paramUrl[0] == "POST") {
                //alert('POST');
                var jsonData = new Array();
                jsonData.push({ paramName: 'cacheKey', paramValue: paramUrl[1] });
                jsonData.push({ paramName: 'pageIndex', paramValue: paramUrl[2] });

                var posturl = methodUrl[0].split('?');

                $("#" + prevLiId.substring(3)).contents().find('body').append('<form action="POST" id="dynamicForm"><input /></form>');

                var dynamicForm = $("#" + prevLiId.substring(3)).contents().find('#dynamicForm');
                dynamicForm.attr('method', 'POST');
                dynamicForm.attr('action', posturl[0]);
                //dynamicForm.setAttribute("method", "POST");
                //dynamicForm.setAttribute("action", posturl[0]);
                dynamicForm.html('');
                //dynamicForm.innerHTML = "";  

                for (var i = 0; i < jsonData.length; i++) {
                    //var input = document.createElement("input");
                    var input = '<input type="" name="' + jsonData[i].paramName + '" value="' + jsonData[i].paramValue + '" />';
                    //input.setAttribute("type", "hidden");
                    //input.setAttribute("name", jsonData[i].paramName);
                    //input.setAttribute("value", jsonData[i].paramValue);
                    //dynamicForm.appendChild(input);
                    dynamicForm.append(input);
                }
                dynamicForm[0].submit();
            }
            else {
                window.frames[prevLiId.substring(3)].location.href(methodUrl[0]);
            }
            //结束
        }
        $('#' + prevLiId).trigger('click');
    }
}
function createIdForIframe() {
    return 'ifr_' + (Math.random() + '').substring(2);
}
function isIframeCanColse() {
    //alert(is_form_changed('form'));
}
function showCurrentLabel(showType,id) {//1:新建 2:移除 3:左移 4: 右移 default: resize
    var labelWrapWidth = $('#iframeLabel').width() - 100;
    var showLabelNumber = Math.floor(($('#iframeLabel').width() - 100) / 106);
    //document.title = showLabelNumber + '|' + labelQueue.length;
    switch (showType) {
        case 1:
            {
                if (labelQueue.length > showLabelNumber) {
                    $('#iframeLabel li').each(function(i, o) {
                        if (i != 0 && labelQueue.length - showLabelNumber +1 > i) {
                            $(o).hide();
                        }
                    });
                    $('.turnBtnLR img:first').attr('src', '/images/tagArrowL.gif');
                }
                break;
            }
        case 2:
            {
                if ($('#li_' + id).next().html() != null && $('#li_' + id).next().css('display') == 'none') {//将右侧label显示
                    $('#li_' + id).next().show();
                }
                else {                                                                                      //将左侧label显示
                    if (labelQueue.length > showLabelNumber) {
                        $('#iframeLabel li:hidden:last').show();
                    }
                }
                break;
            }
        case 3:
            {
                var leftLabel = $('#iframeLabel li:visible').eq(1);
                var rightLabel = $('#iframeLabel li:visible:last');
                if (leftLabel.prev().html() != null && leftLabel.prev().prev().html() != null) {
                    if ($('#iframeLabel li:visible').length - 1 == showLabelNumber) {

                        leftLabel.prev().show();
                        rightLabel.hide();
                    }
                    else {
                        leftLabel.show();
                    }
                }
                else {
                    $('.turnBtnLR img:first').attr('src', '/images/tagArrowL2.gif');
                }
                break;
            }
        case 4:
            {
                var leftLabel = $('#iframeLabel li:visible').eq(1);
                var rightLabel = $('#iframeLabel li:visible:last');
                if (rightLabel.next().html() != null) {
                    if ($('#iframeLabel li:visible').length - 1 == showLabelNumber) {
                        rightLabel.next().show();
                        leftLabel.hide();
                    }
                }
                break;
            }
        default:
            {
                if ($('#iframeLabel li').length < 1) return;
                var leftLabel = $('#iframeLabel li:visible').eq(1);
                var rightLabel = $('#iframeLabel li:visible:last');

                if ($('#iframeLabel li:visible').length - 1 > showLabelNumber) {//大->小
                    $('#iframeLabel li:visible').each(function(i, o) {
                        if (i != 0 && $('#iframeLabel li:visible').length + 1 - showLabelNumber > i) {
                            $(o).hide();
                        }
                    });
                }
                else {
                    var leftLaybelIndex = 0;
                    var rightLaybelIndex = 0;
                    $('#iframeLabel li').each(function(i, o) {
                        if (leftLabel.attr('id') == $(o).attr('id')) {
                            leftLaybelIndex = i;
                        }
                        if (rightLabel.attr('id') == $(o).attr('id')) {
                            rightLaybelIndex = i;
                        }
                    });

                    if (labelQueue.length - showLabelNumber > 0) {
                        if (labelQueue.length - showLabelNumber > leftLabel) {
                            $('#iframeLabel li').each(function(i, o) {
                                if (i != 0 && i > leftLabel)
                                    $(o).show();
                            });
                        }
                        else {
                            var temp = labelQueue.length - showLabelNumber;
                            $('#iframeLabel li').each(function(i, o) {
                                if (i > temp)
                                    $(o).show();
                            });
                        }
                    }
                    else {
                        $('#iframeLabel li').each(function(i, o) {
                            if (i != 0)
                                $(o).show();
                        });
                    }
                }


                break;
            }
            
    }

}

function showDesk() { 
    $('#MDI_Forms div').hide();
    $('#MDI_Forms div:first').show();
    $('#iframeLabel li').removeClass('currentTagNav').addClass('otherTagNav');
    $('#iframeLabel li:first').addClass('currentTagHome').addClass('tagHome').removeClass('otherTagNav');
    $('ul[class=secondNav]').hide();
}

//2009-4-21  mode = true， 新开页问题。
//2009-4-22  106|78 超出处理。
//2009-4-23  resize

function is_form_changed(f) {
    var changed = false;
    $(':text, :password, textarea', f).each(function() {
        var _v = $(this).attr('_value');
        if (typeof (_v) == 'undefined') _v = '';
        if (_v != $(this).val()) changed = true;
    });

    $(':checkbox, :radio', f).each(function() {
        var _v = this.checked ? 'on' : 'off';
        if (_v != $(this).attr('_value')) changed = true;
    });

    $('select', f).each(function() {
        var _v = $(this).attr('_value');
        if (typeof (_v) == 'undefined') _v = '';
        var selectIndex = this.selectedIndex;
        var selectValue = selectIndex > -1 ? this.options[selectIndex].value : "";
        if (_v != selectValue) changed = true;
    });
    return false;
}


function isCloseForm() {
    var returnVal = true;
    try {
        if (typeof (is_form_changed) == "function") {
            if (is_form_changed($('form'))) {
                returnVal = window.confirm('确实要离开页面吗?\n\n你正在编辑并没有保存，点击“确定”将丢失您所编辑的内容！\n\n按“确定”继续，或按“取消”留在当前页面。');
            }
            return true;
        }
    }
    catch (e) {
        return true;
    }

    finally {if (returnVal) return true; else {return false;} }
}

//子窗口新开标签页
function openFromIframe(caption, url, mode, menuPath, needBack) {
    var oLi = $('#iframeLabel', parent.document).find('li[class=currentTagNav]');
    if (caption == '') caption = oLi.text(); //
    if (menuPath == '') menuPath = $('li[class*=currentNav]', parent.document).attr('id'); //树目录状态驻留ID
    //alert(menuPath);
    parent.openIframe(caption, url, mode, menuPath,needBack);
}

/*
提交表单时打开,参数说明：
jqueryForm为表单的jquery对象；
fromMainPage：是否在主窗口打开，bool；
caption为标签标题；
url为页面打开页面URL；
mode设置是否允许开始多次，
bool；menuPath为左侧功能树对应标识。
*/
function openFromForm(jqueryForm, fromMainPage, caption, url, mode, menuPath) {
    tName = fromMainPage ? openIframe(caption, url, mode, menuPath) : openFromIframe(caption, url, mode, menuPath);
    if(tName==undefined)return;
    if (fromMainPage) {
        jqueryForm.attr('target', tName);
    }
    else {
        jqueryForm.attr('target', tName);
    }
    jqueryForm[0].submit();
}

//子窗口设置标签名
function setLabelFromIframe(newName) {
    $('#iframeLabel li[class="currentTagNav"]', (window.parent.document)).find('span:last').html(newName);
}

//子窗口关闭标签页
function colseFromIframe() {
    $('#iframeLabel li[class="currentTagNav"] a', (window.parent.document)).trigger('click');
}

//关闭除桌面外所有标签页,主窗体调用设置参数为true;
function closeAllIframe(inMainPage) {
    if (!labelQueue.length) { alert('没有可以关闭的标签页。'); return; }
    if (!window.confirm('您确定要关闭所有已打开的标签窗口吗？')) return;
    if (inMainPage) {
        $('#iframeLabel li:gt(0)').remove();
        $('#MDI_Forms div:gt(0)').remove();
    }
    else {
        $('#iframeLabel li:gt(0)', window.parent.document).remove();
        $('#MDI_Forms div:gt(0)', window.parent.document).remove();
    }
    labelQueue.length = 0;
    urlQueue.length = 0;
    stateQueue.length = 0;
    showDesk();
}


function setFixRowTable(th, tb) {
    $('tr:first td', th).each(function(i, o) {
        $('tr:first td', tb).eq(i).width($(this).width());
    });
}


///BenCham
function showWatting() {
    $.blockUI({ message: $('#ProcessingPanel') });
}

function hideWatting() {
    $.unblockUI();
}

///End BenCham


function mul(n1, n2) {
    var m = 0, s1 = n1.toString(), s2 = n2.toString();
    try {
        m += s1.split(".")[1].length
    } catch (e) {
    }
    try {
        m += s2.split(".")[1].length
    } catch (e) {
    }
    return Number(s1.replace(".", "")) * Number(s2.replace(".", "")) / Math.pow(10, m);
}

//减法
function accSub(arg1, arg2) {
    var r1, r2, m, n;
    try { r1 = arg1.toString().split(".")[1].length } catch (e) { r1 = 0 }
    try { r2 = arg2.toString().split(".")[1].length } catch (e) { r2 = 0 }
    m = Math.pow(10, Math.max(r1, r2));
    //last modify by deeka
    //动态控制精度长度
    n = (r1 >= r2) ? r1 : r2;
    return ((arg1 * m - arg2 * m) / m).toFixed(n);
}

//除法
function accDiv(arg1,arg2){ 
    var t1=0,t2=0,r1,r2; 
    try{t1=arg1.toString().split(".")[1].length}catch(e){} 
    try{t2=arg2.toString().split(".")[1].length}catch(e){}
    with (Math) {
        r1 = Number(arg1.toString().replace(".", ""))
        r2 = Number(arg2.toString().replace(".", ""))
        return (r1 / r2) * pow(10, t2 - t1);
    } 
} 

//乘法
function accMul(arg1,arg2) 
{ 
    var m=0,s1=arg1.toString(),s2=arg2.toString(); 
    try{m+=s1.split(".")[1].length}catch(e){} 
    try{m+=s2.split(".")[1].length}catch(e){} 
    return Number(s1.replace(".",""))*Number(s2.replace(".",""))/Math.pow(10,m); 
}  

//加法
function accAdd(arg1,arg2){ 
    var r1,r2,m; 
    try{r1=arg1.toString().split(".")[1].length}catch(e){r1=0} 
    try{r2=arg2.toString().split(".")[1].length}catch(e){r2=0} 
    m=Math.pow(10,Math.max(r1,r2)) 
    return (arg1*m+arg2*m)/m;
}

window.redirect = function(url) {
    //openFromIframe("", encodeURI(url), false, "");
    window.location.href = encodeURI(url);
};


window.redirectbyWait = function(url) {
    showWaitting();
    setTimeout(function() { window.redirect(url) }, 1);
}

function showWaitting() {
    var oLi = $('#iframeLabel', parent.document).find('li[class=currentTagNav]');
    $.blockUI({ message: '<img src="/images/iframe_loading.gif" alt="" />&nbsp;&nbsp;数据处理中，请稍后......',
        css: { background: 'white', border: '0px solid #a00' },
        overlayCSS: { backgroundColor: '#000000', opacity: '0.3' }, fadeIn: 0
    });
}

function closeWaitting() {
    $.unblockUI();
}

function showLoading() {
    $('#iframe_loading').hide();
    $('#iframe_loading').css('top', $(window).height() / 2);
    $('#iframe_loading').css('left', ($(window).width() - 200) / 2);
    $('#iframe_loading').show();
}        //junp 05-13 打开标签页时的loading效果
function hideLoading() {
    $('#iframe_loading').hide();
}



function openBackPage(url) {
    var i = 0;
    var temUrl = url;
    var methodUrl = url.split('|||');
    while (methodUrl.length < 2 && i < 10) {
        temUrl = decodeURIComponent(temUrl);
        methodUrl = temUrl.split('|||');
        i++;
    }

    //var methodUrl = decodeURIComponent(decodeURIComponent(url)).split('|||');
    var paramUrl = methodUrl[1].split('~~');
    if (paramUrl[0] == "POST") {
        var jsonData = new Array();
        jsonData.push({ paramName: 'cacheKey', paramValue: paramUrl[1] });
        jsonData.push({ paramName: 'pageIndex', paramValue: paramUrl[2] });
        
        var posturl = methodUrl[0].split('?');
        $('body').append('<form action="POST" id="dynamicForm"></form>');
        var dynamicForm = document.getElementById("dynamicForm");
        dynamicForm.setAttribute("method", "POST");
        dynamicForm.setAttribute("action", posturl[0]);
        dynamicForm.innerHTML = "";
        for (var i = 0; i < jsonData.length; i++) {
            var input = document.createElement("input");
            input.setAttribute("type", "hidden");
            input.setAttribute("name", jsonData[i].paramName);
            input.setAttribute("value", jsonData[i].paramValue);
            dynamicForm.appendChild(input);
        }
        showWaitting();
        dynamicForm.submit();
    }
    else {
        window.redirectbyWait(methodUrl[0]);
    }
}

function QueryString(item) {
    var sValue = location.search.match(new RegExp("[\?\&]" + item + "=([^\&]*)(\&?)", "i"))
    return sValue ? sValue[1] : sValue;
}

//会返回地址的提交方式
function EidtFormSubmit(formName) {
    var urlBack = QueryString('urlBack');
    var dynamicForm = document.getElementById(formName);
    var input = document.createElement("input");
    input.setAttribute("type", "hidden");
    input.setAttribute("name", "urlBack");
    input.setAttribute("value", urlBack);
    dynamicForm.appendChild(input);
    showWaitting();
    
    document.getElementById(formName).submit();
}

//检查form数据是否正确,并提交
function AjaxCheck(datatype, fromname) {
    var json = { datatype: datatype, r: Math.random() };
    $("#form1 [name]").each(function() {
        var key = $(this).attr("name");
        var val = $(this).val();
        if (key.substring(0, 2) == "sm")
            val = val + "|" + $("#psc" + key.substring(2, key.length)).html();
        else val = val + "|";
        if (json[key] == undefined || json[key] == "")
            json[key] = val;
        else json[key] = json[key] + "," + $(this).val();
    })

    $.post("/MarkOutModule/CheckPropertySuccess", json, function(result) {
        if (result != undefined && result != null && result != '') {
            alert(result);
            return;
        }
        EidtFormSubmit(fromname);
    }); 
    //setInterval(function(){},100);
}

//检查form数据是否正确
function AjaxOnlyCheck(datatype, fromname) {
    var json = { datatype: datatype, r: Math.random() };
    $("#form1 [name]").each(function() {
        var key = $(this).attr("name");
        var val = $(this).val();
        if (key.substring(0, 2) == "sm")
            val = val + "|" + $("#psc" + key.substring(2, key.length)).html();
        else val = val + "|";
        if (json[key] == undefined || json[key] == "")
            json[key] = val;
        else json[key] = json[key] + "," + $(this).val();
    })

    $.post("/MarkOutModule/CheckPropertySuccess", json, function(result) {
        if (result != undefined && result != null && result != '') {
            alert(result);
            return false;
        }
        return true;
    });
}

//获取SM的JOSN
function GetsmJson(id) {
    var json = { r: Math.random() };
    $("#" + id + " [name]").each(function() {
        var key = $(this).attr("name");
        var val = $(this).val();
        if (json[key] == undefined || json[key] == "")
            json[key] = val;
        else json[key] = json[key] + "," + $(this).val();
    })
    return json;
}

///目录树消息提示
function GetImmediateMessage() {
    var testData = new Array();//测试数据
    testData.push(new Array('MessageModule___NewMessage', 3));
    testData.push(new Array('MessageModule___Employee', 2));
    testData.push(new Array('MessageModule___Draftbox', 1));
    testData.push(new Array('MessageModule___Mailbox', 2));
    testData.push(new Array('MessageModule___SendedMessage', 5));
    testData.push(new Array('MessageModule___DeletedMessage', 9));

    var len = testData.length;
    for (var i = 0; i < len; i++) {
        if ($('#' + testData[i][0]).find('span:first').length > 0) {
            $('#' + testData[i][0]).find('b').remove();
            $('#' + testData[i][0]).find('span:first').append('<b style="color:#999;font-weight:normal;">(<strong style="color:red;font-weight:normal;">' + testData[i][1] + '</strong>)</b>');
        }
    }
}


//信息模块选择联系人
var mailAddressHelper = {};
mailAddressHelper.overColor = '#E0ECF9';
mailAddressHelper.selectColor = '#528cbc';
mailAddressHelper.addressColor = '#aaaaaa';
mailAddressHelper.address = [];
mailAddressHelper.form = '';
mailAddressHelper.inputType = '';
//拆分地址
mailAddressHelper.getAddressInfo = function(str) {
    this.getAddressInfo.name = str.split('<')[0];
    this.getAddressInfo.address = str.split('<')[1].split('>')[0];
    return this.getAddressInfo;
};

mailAddressHelper.mouseover = function(obj, color) {
    $(obj).unbind().hover(function() {
        if ($(obj).css('background')) {
            if (mailAddressHelper.selectColor.toLowerCase() != $(obj).css('background').toLowerCase())
                $(obj).css('background', color);
        }
        else {
            $(obj).css('background', color);
        }
    }, function() {
        if ($(obj).css('background') && ($(obj).css('background').toLowerCase() == color.toLowerCase())) {
            $(obj).css('background', '');
        }
    });
}

//高亮
mailAddressHelper.hightlight = function(obj, color) {
    if ($('#hidInput').length < 1) { $(document.body).append('<input type="text" id="hidInput" style="position:absolute;left:-999px;top:-999px;" />') };
    document.getElementById('hidInput').focus(); //转移焦点，避免Backspace键盘误操作
    $(obj).parent().find('li').css('background', '');
    if ($(obj).css('background').toLowerCase() == mailAddressHelper.selectColor) {
        $(obj).css('background', '');
    } else {
        $(obj).css('background', mailAddressHelper.selectColor);
    }
}

//移除
mailAddressHelper.removeItem = function() {
    $('div[empGuid]').each(function(i, o) {
        if ($(o).css('background') && ($(o).css('background').toLowerCase() == mailAddressHelper.selectColor.toLowerCase())) {
            $(o).remove();
        }
    });

}

//弹出选择联系人页面，参数：containerId，容器ID，strlType('radion','checkbox')
mailAddressHelper.ShowEmployee = function(containerId, ctrlType, dept, job) {
    $(document).unbind('onkeydown');
    //    document.onkeydown = function() {
    //        if (event.keyCode == 8 || event.keyCode == 46) {
    //            mailAddressHelper.removeItem();
    //        }
    //    };
    mailAddressHelper.from = containerId;
    mailAddressHelper.inputType = ctrlType;
    if (arguments.length == 4) {
        window.showModalDialog('/MessageModule/Showemployee?r=' + Math.random()+'&dept='+dept+'&job='+job, window, 'status:no;resizable:yes;dialogHeight:460px;dialogWidth:720px');
    }
    else {
        window.showModalDialog('/MessageModule/Showemployee?r=' + Math.random(), window, 'status:no;resizable:yes;dialogHeight:460px;dialogWidth:720px');
    }
}

//获取员工GUID，参数：容器ID;返回值：guid1;guid2;guid3，没有值则返回false 
mailAddressHelper.GetEmployeeGuid = function(t) {
    var temp = '';
    $('#' + t + '>div').each(function(i, o) {
        temp += $(o).attr('empGuid') + ';';
    });
    return temp.length > 0 ? temp.substring(0, temp.length - 1) : false;
}

function pageX(elem) {
    return elem.offsetParent ? (elem.offsetLeft + pageX(elem.offsetParent)) : elem.offsetLeft;
}
function pageY(elem) {
    return elem.offsetParent ? (elem.offsetTop + pageY(elem.offsetParent)) : elem.offsetTop;
}


var et_drag = {};
et_drag.on = false;
et_drag.url = '';
et_drag.guid = '';
et_drag.path = '';
et_drag.defaultTip = '拖到对应图标可以查看相关信息';
et_drag.type = '';
et_drag.labelname = '';
et_drag.icon = '';

et_drag.dragAndOpen = function(guid, mode, type) {
    et_drag.guid = guid;
    et_drag.type = type;
    //添加遮罩层，避免层在经过iframe时不流畅
    if (!$('#drag').length > 0) $(document.body).append('<div style="position:absolute;left:0;top:0;width:2000px;height:2000px;"><div id="drag" style="display:none;position: absolute;border:1px solid #aaa;height:24px;background:#FFFDAA url(/images/dragNO.gif) no-repeat;line-height:24px;text-indent:30px;text-overflow:ellipsis;overflow:hidden;padding-right:5px;" class="handle">' + et_drag.defaultTip + '</div></div>');
    $(document.body).bind('mousemove', function(event) {
        $('#drag').css({
            top: (event.originalEvent.y || event.originalEvent.layerY || 0) - 30,
            left: (event.originalEvent.x || event.originalEvent.layerX || 0) + 8
        });
        //$('#drag').html(et_drag.on+'|'+Math.random());
        //改变提示移动层样式
        et_drag.on ? $('#drag').css('background', '#FFFDAA url(/images/dragOK.gif) no-repeat') : $('#drag').css('background', '#FFFDAA url(/images/dragNO.gif) no-repeat');
        $('#drag').show();
    })
    .bind('mouseup', function() {
        $('#drag').parent().remove(); //移除遮罩
        $(document.body).unbind('mousemove'); //解除鼠标移动事件绑定
        if (et_drag.on) {
            openIframe(et_drag.labelname, et_drag.url, mode, et_drag.path);
        } $(document.body).unblind('mouseup');
    });

}

et_drag.buildUrl = function(labelname, tip, url, path) {
    et_drag.icon = this;
    alert(et_drag.icon.attr('src'));
    var index = et_drag.type == 'station' ? 1 : 0;
    et_drag.url = url[index] + et_drag.guid;
    et_drag.on = true;
    et_drag.labelname = labelname[index];
    et_drag.path = path[index];
    $('#drag').html(tip[index]);
}
et_drag.reset = function() {
    et_drag.on = false;
    $('#drag').html(et_drag.defaultTip);
}

var dragTable = {};
dragTable.orTdNum;
dragTable.onTdNum;
dragTable.mx = '';
dragTable.my = '';
dragTable.style_mouseon = 'on';
dragTable.style_borderTop = 'borderTop';
dragTable.style_borderBottom = 'borderBottom';
dragTable.style_original = 'or';
dragTable.dragTd = function(dragHandle) {
    var tdObj = $(dragHandle);
    dragTable.dragtding = true;
    $(tdObj).addClass('or');
    if (!$('#dragTableTempDiv').length > 0) {
        $(document.body).append('<div id="dragTableTempDiv" style="position:absolute;background:#fff;display:none;">' + $(tdObj).html() + '</div>');
        $('#dragTableTempDiv').css({ width: $(tdObj).width(), height: $(tdObj).height() });
    }
    $(document.body).bind('mousemove', function(event) {
        $('#dragTableTempDiv').css({
            top: (event.originalEvent.y || event.originalEvent.layerY)+5,
            left: (event.originalEvent.x || event.originalEvent.layerX)+5
        });
        $('#dragTableTempDiv').show();
    })
	.bind('mouseup', function() {
	    if ($('td[class=' + dragTable.style_mouseon + ']').length > 0 && dragTable.orTdNum == dragTable.onTdNum) {
	        var temp = $('td[class=' + dragTable.style_mouseon + ']').html();
	        $('td[class=' + dragTable.style_mouseon + ']').html($('#dragTableTempDiv').html());
	        $('td[class=' + dragTable.style_original + ']').html(temp);

	    } 
	    $(tdObj).removeClass(dragTable.style_original);
	    $('#dragTableTempDiv').remove();
	    $(document.body).unbind().find('td').removeClass(dragTable.style_mouseon);
	    dragTable.dragtding = false;
	    dragTable.bindevent();
	});
};

dragTable.dragTr = function(dragHandle) {
    var trObj = $(dragHandle).next();
    dragTable.dragtring = true;
    $('tr[class*=' + dragTable.style_original + ']').removeClass(dragTable.style_original);
    $(trObj).addClass(dragTable.style_original);
    if (!$('#dragTableTempDiv').length > 0) {
        $(document.body).append('<div id="dragTableTempDiv" style="position:absolute;background:#fff;display:none;"><table><tr class="handle" move="handle">' + $(dragHandle).html() + '</tr><tr>' + $(trObj).html() + '</tr></table></div>');
        $('#dragTableTempDiv').css({ width: $(trObj).width(), height: $(trObj).height() });
    }
    $(document.body).bind('mousemove', function(event) {
        dragTable.mx = event.originalEvent.x || event.originalEvent.layerX;
        dragTable.my = event.originalEvent.y || event.originalEvent.layerY;
        $('#dragTableTempDiv').css({
            top: dragTable.my+5,
            left: dragTable.mx+5
        });
        $('#dragTableTempDiv').show();
        if (dragTable.y > dragTable.my) {
            $('tr[class*=' + dragTable.style_mouseon + ']').prev().find('td').addClass(dragTable.style_borderTop);
            //if($('tr[class*='+dragTable.style_mouseon+']').prev().html()!=null){
            //$('tr[class*='+dragTable.style_mouseon+']').prev().find('td').addClass(dragTable.style_borderBottom);
            //}
        }
        else {
            $('tr[class*=' + dragTable.style_mouseon + ']').find('td').addClass(dragTable.style_borderBottom);
            //if($('tr[class*='+dragTable.style_mouseon+']').next().html()!=null){
            //	$('tr[class*='+dragTable.style_mouseon+']').next().find('td').addClass(dragTable.style_borderTop);
            //}
        }

    })
	.bind('mouseup', function(event) {
	    var tempY = event.originalEvent.y || event.originalEvent.layerY;
	    $(trObj).removeClass(dragTable.style_mouseon);
	    if ($('tr[class*=' + dragTable.style_mouseon + ']').length > 0) {
	        var temptr = $('tr[class=' + dragTable.style_original + ']');
	        var handletr = $('tr[class=' + dragTable.style_original + ']').prev();
	        //if(temptr.size()==1&&handletr.size()==1){
	        if (dragTable.y > tempY) {
	            $('tr[class*=' + dragTable.style_mouseon + ']').prev().before('<tr class="handle" move="handle">' + handletr.html() + '</tr><tr>' + temptr.html() + '</tr>');
	        }
	        else {
	            $('tr[class*=' + dragTable.style_mouseon + ']').after('<tr class="handle" move="handle">' + handletr.html() + '</tr><tr>' + temptr.html() + '</tr>');
	        }
	        handletr.remove();
	        temptr.remove();
	        //}
	    }
	    $('#dragTableTempDiv').remove();
	    $(document.body).unbind().find('tr').removeClass(dragTable.style_mouseon);
	    dragTable.dragtring = false;
	    dragTable.bindevent();
	});
};

dragTable.addRow = function(text,key) {
    var html = '';
    html = text.length == 2 ? "<tr class=\"handle\" move=\"handle\"><td colspan=\"2\">&nbsp;</td></tr><tr><td  move='handle'>" + text[0] + "<input type='hidden' value='" + key[0] + "' /></td><td  move='handle'>" + text[1] + "<input type='hidden' value='" + key[1] + "' /></td></tr>" : "<tr class=\"handle\" move=\"handle\"><td colspan=\"2\">&nbsp;</td></tr><tr><td  move='handle' colspan='2'>" + text[0] + "<input type='hidden' value='" + key[0] + "' /></td></tr>";
    $('table[class*=dragTable]').append(html);
    dragTable.bindevent();
};

dragTable.getValue = function() {
    var temp = '';
    var spe = '';
    $('table[class=dragTable]').find('tr:odd td').each(function(i, o) {
        temp += spe + $(o).find('input').val() + '|' + $(o).attr('colspan');
        spe = ';';
    });
    return temp;
}

dragTable.bindevent = function() {
    $('td[move=handle]').unbind().mousedown(function() {
        dragTable.dragTd(this);
        dragTable.orTdNum = $(this).parent().find('td').size();
    })
		.bind('mouseover', function() {
		    if (dragTable.dragtding) {
		        dragTable.onTdNum = $(this).parent().find('td').size();
		        $(this).addClass(dragTable.style_mouseon);
		    }
		})
		.bind('mouseout', function() {
		    if (dragTable.dragtding)
		        $(this).removeClass(dragTable.style_mouseon);
		});

    $('tr[move=handle]').unbind().mousedown(function(event) {
        dragTable.dragTr(this);
        dragTable.y = event.originalEvent.y || event.originalEvent.layerY;
    }).next()
		.bind('mouseover', function() {
		    if (dragTable.dragtring) {
		        //$('tr[class='+dragTable.style_mouseon+']').removeClass(dragTable.style_mouseon);
		        $(this).addClass(dragTable.style_mouseon);
		    }
		})
		.bind('mouseout', function() {
		    if (dragTable.dragtring) {
		        $(this).removeClass(dragTable.style_mouseon);
		        $(this).parent().find('td').removeClass(dragTable.style_borderTop).removeClass(dragTable.style_borderBottom);
		    }
		})
		.bind('mouseup', function() {
		    if (dragTable.dragtring) {
		        $(this).parent().find('td').removeClass(dragTable.style_borderTop).removeClass(dragTable.style_borderBottom);
		    }
		});
}



var et_calendar = {};
et_calendar.plan = [];
et_calendar.dateObj = new Date();

et_calendar.getDaysOfMonth = function(month, year) {//月对应天数
    return (new Date(year, month, 0)).getDate();
}

et_calendar.year = et_calendar.dateObj.getYear();
et_calendar.month = et_calendar.dateObj.getMonth();
et_calendar.currentDay = et_calendar.dateObj.getDate();
et_calendar.isToday = true;
et_calendar.pass = false;
et_calendar.hasPlan = false;
et_calendar.ajaxUrl = '';
et_calendar.newPlanUrl = '';
et_calendar.path = '';
et_calendar.ifHasPlan = function(ymd, day) {
    if (ymd[0] == et_calendar.year && ymd[1] == et_calendar.month+1 && ymd[2] == day) {
        return true;
    }
    return false;
}

et_calendar.update = function(month) {
    if (month == 'prev') {
        et_calendar.month--;
        if (et_calendar.month < 0) {
            et_calendar.month = 11;
            et_calendar.year--;
        }
    }
    if (month == 'next') {
        et_calendar.month++;
        if (et_calendar.month > 11) {
            et_calendar.month = 0;
            et_calendar.year++;
        }
    }
    et_calendar.isToday = false;
    if (et_calendar.year == et_calendar.dateObj.getYear() && et_calendar.month == et_calendar.dateObj.getMonth()) {
        et_calendar.isToday = true;
    }
    et_calendar.pass = new Date(et_calendar.dateObj.getYear(), et_calendar.dateObj.getMonth()) > new Date(et_calendar.year, et_calendar.month);
    $('#calendar_wrap').html(et_calendar.displayCalendar());
}

et_calendar.getPlans = function(date) {
    $.get(et_calendar.ajaxUrl + date + '&r=' + Math.random(), function(result) {
        $('#dayPlan').html(result);
    });
}

et_calendar.newPlan = function(date) {
    openFromIframe('新建日程', et_calendar.newPlanUrl + date, false, et_calendar.path);
}

et_calendar.displayCalendar = function() {
    var result = "<table><tr align=middle><th width=20>日</th><th width=20>一</th><th width=20>二</th><th width=20>三 </th><th width=20>四</th><th width=20>五</th><th width=20>六</th></tr></table><table>";
    //更新年
    $('#yyyy').html(et_calendar.year);
    //更新月
    $('#mm').html(et_calendar.month + 1);
    et_calendar.firstDay = (new Date(et_calendar.year, et_calendar.month, 1)).getDay();
    et_calendar.lastDay = et_calendar.getDaysOfMonth(et_calendar.month + 1, et_calendar.year);
    //alert(et_calendar.firstDay+'='+et_calendar.currentDay+'='+et_calendar.month);
    var curCell = 0;
    var day = 0;
    for (i = 0; i < 6; i++) {
        result += ' <tr><td style="color:#999;"><table><tr> ';
        for (j = 0; j < 7; j++) {
            result += '<td align="center" width="20"';
            if (curCell < et_calendar.firstDay) {
                result += '>&nbsp;</td>';
            }
            else {
                day++;
                if (day <= et_calendar.lastDay) {
                    if (et_calendar.pass) {
                        result += ' style="color:#aaa;">' + day + '</td>';
                    }
                    else {
                        for (var kk = 0; kk < et_calendar.plan.length; kk++) {
                            if (et_calendar.ifHasPlan(et_calendar.plan[kk], day)) {
                                et_calendar.hasPlan = true;
                            }
                        }
                        if (et_calendar.isToday) {
                            if (et_calendar.currentDay < day) {
                                
                                if (et_calendar.hasPlan) {
                                    result += ' class="work" style="color:#fff;" onclick="et_calendar.getPlans(\'' + et_calendar.year + '-' + (et_calendar.month + 1) + '-' + day + '\');">' + day + '</td>';
                                }
                                else {
                                    result += ' class="valid" title="双击添加日程" ondblclick=\"et_calendar.newPlan(\'' + et_calendar.year + '-' + (et_calendar.month + 1) + '-' + day + '\');\">' + day + '</td>';
                                }
                            }
                            else if (et_calendar.currentDay == day) {
                                if (et_calendar.hasPlan) {
                                    result += ' class="work" style="color:#fff;" onclick="et_calendar.getPlans(\'' + et_calendar.year + '-' + (et_calendar.month + 1) + '-' + day + '\');">' + day + '</td>';
                                }
                                else {
                                    result += ' class="current" style="color:#fff;">' + day + '</td>';
                                }

                            }
                            else {
                                result += ' style="color:#aaa;">' + day + '</td>';
                            }
                        }
                        else {

                            if (et_calendar.hasPlan) {
                                result += ' class="work" style="color:#fff;" onclick="et_calendar.getPlans(\'' + et_calendar.year + '-' + (et_calendar.month + 1) + '-' + day + '\');">' + day + '</td>';
                            }
                            else {
                                result += ' class="valid" title="双击添加日程" ondblclick=\"et_calendar.newPlan(\'' + et_calendar.year + '-' + (et_calendar.month + 1) + '-' + day + '\');\">' + day + '</td>';
                            }

                        }
                    } et_calendar.hasPlan = false;
                }
                else {
                    result += '>&nbsp;</td>';
                }
            }
            curCell++;
        }
        result += '</tr></table></td></tr>';
    }
    return (result + '</table>');
}


var inputHelper = {};
inputHelper.defaultValue = '';
inputHelper.setting = function(val, obj) {
    inputHelper.defaultValue = val;
    if (inputHelper.defaultValue == $(obj).val()) {
        $(obj).val('');
    }

    $(obj).bind('blur', function() {
        if ($(obj).val() == '') {
            $(obj).val(inputHelper.defaultValue);
        }
    });
}


/*
输入提示
用法：

获焦提示：onfocus = inputTips.show(el,mes);
失焦 onblur = inputTips.hide(el);
*/

var $$$ = function(id) {
    return "string" == typeof id ? document.getElementById(id) : id;
};


var isIE6 = navigator.userAgent.indexOf('MSIE 6.0') != -1;
var isIE8 = navigator.userAgent.indexOf('MSIE 8.0') != -1;
var isChrome = navigator.userAgent.indexOf('Chrome') != -1;
var isSafari = navigator.userAgent.indexOf('AppleWebKit') != -1;

// with input from Tino Zijdel, Matthias Miller, Diego Perini 
// http://dean.edwards.name/weblog/2005/10/add-event/ 
function tipaddEvent(element, type, handler) {
    if (element.addEventListener) {
        element.addEventListener(type, handler, false);
    } else {
        if (!handler.$$$guid) handler.$$$guid = addEvent.guid++;
        if (!element.events) element.events = {};
        var handlers = element.events[type];
        if (!handlers) {
            handlers = element.events[type] = {};
            if (element["on" + type]) {
                handlers[0] = element["on" + type];
            }
        }
        handlers[handler.$$$guid] = handler;
        element["on" + type] = tiphandleEvent;
    }
};
tipaddEvent.guid = 1;

function tiphandleEvent(event) {
    var returnValue = true;
    event = fixEvent(event);
    var handlers = this.events[event.type];
    for (var i in handlers) {
        this.$$$tiphandleEvent = handlers[i];
        if (this.$$$tiphandleEvent(event) === false) {
            returnValue = false;
        }
    }
    return returnValue;
};
function tipfixEvent(event) {
    if (event) return event;
    event = ((this.ownerDocument || this.document || this).parentWindow || window).event;
    var scrolldoc = isChrome || isSafari ? document.body : document.documentElement;
    event.pageX = event.clientX + scrolldoc.scrollLeft;
    event.pageY = event.clientY + scrolldoc.scrollTop;
    event.target = event.srcElement;
    event.stopPropagation = tipfixEvent.stopPropagation;
    event.preventDefault = tipfixEvent.preventDefault;
    if (event.type == "mouseout") {
        event.relatedTarget = event.toElement;
    } else if (event.type == "mouseover") {
        event.relatedTarget = event.fromElement;
    }
    return event;
};
tipfixEvent.preventDefault = function() {
    this.returnValue = false;
};
tipfixEvent.stopPropagation = function() {
    this.cancelBubble = true;
};

var tipExtend = function(destination, source) {
    for (var property in source) {
        destination[property] = source[property];
    }
    return destination;
}



var BindAsEventListener = function(object, fun) {
    var args = Array.prototype.slice.call(arguments, 2);
    return function(event) {
        return fun.apply(object, [event].concat(args));
    }
}

function GetRelative(relElem, fixedElem, tipoptions) {
    var doc = relElem.ownerDocument, docElem = doc.documentElement
		, scrolldoc = isChrome || isSafari ? doc.body : docElem,
		rect = relElem.getBoundingClientRect();
    //默认值
    tipoptions = tipExtend({
        Align: "clientleft", //水平方向定位
        vAlign: "clienttop", //垂直方向定位
        CustomLeft: 0, //自定义left定位
        CustomTop: 0, //自定义top定位
        PercentLeft: 0, //自定义left百分比定位
        PercentTop: 0, //自定义top百分比定位
        Adaptive: false, //是否自适应定位
        Reset: false//自适应定位时是否重新定位
    }, tipoptions || {});
    //ie8的getBoundingClientRect获取不准确
    if (isIE8) {
        var elem = relElem, left = -scrolldoc.scrollLeft, top = -scrolldoc.scrollTop;
        while (elem) { left += elem.offsetLeft, top += elem.offsetTop; elem = elem.offsetParent; };
        rect.left = left; rect.right = left + relElem.offsetWidth;
        rect.top = top; rect.bottom = top + relElem.offsetHeight;
    };
    //定义参数
    var iLeft = GetRelative.Left(tipoptions.Align, rect, fixedElem) + tipoptions.CustomLeft
		, iTop = GetRelative.Top(tipoptions.vAlign, rect, fixedElem) + tipoptions.CustomTop;
    //自定义百分比定位
    if (tipoptions.PercentLeft) { iLeft += .01 * tipoptions.PercentLeft * relElem.offsetWidth; };
    if (tipoptions.PercentTop) { iTop += .01 * tipoptions.PercentTop * relElem.offsetHeight; };
    //自适应视窗定位
    if (tipoptions.Adaptive) {
        //修正定位参数
        var maxLeft = docElem.clientWidth - fixedElem.offsetWidth,
			maxTop = docElem.clientHeight - fixedElem.offsetHeight;
        if (tipoptions.Reset) {
            //自动重新定位
            if (iLeft > maxLeft || iLeft < 0) {
                iLeft = GetRelative.Left(2 * iLeft > maxLeft ? "left" : "right", rect, fixedElem) + tipoptions.CustomLeft;
            };
            if (iTop > maxTop || iTop < 0) {
                iTop = GetRelative.Top(2 * iTop > maxTop ? "top" : "bottom", rect, fixedElem) + tipoptions.CustomTop;
            };
        } else {
            //修正到适合位置
            iLeft = Math.max(Math.min(iLeft, maxLeft), 0);
            iTop = Math.max(Math.min(iTop, maxTop), 0);
        };
    };
    //加上滚动条
    iLeft += scrolldoc.scrollLeft; iTop += scrolldoc.scrollTop;
    //返回定位参数
    return { Left: iLeft, Top: iTop };
};
GetRelative.Left = function(align, rect, fixedElem) {
    var iLeft = 0;
    switch (align.toLowerCase()) {
        case "left":
            return rect.left - fixedElem.offsetWidth;
        case "clientleft":
            return rect.left;
        case "center":
            return (rect.left + rect.right - fixedElem.offsetWidth) / 2;
        case "clientright":
            return rect.right - fixedElem.offsetWidth;
        case "right":
        default:
            return rect.right;
    };
};
GetRelative.Top = function(valign, rect, fixedElem) {
    var iTop = 0;
    switch (valign.toLowerCase()) {
        case "top":
            return rect.top - fixedElem.offsetHeight;
        case "clienttop":
            return rect.top;
        case "center":
            return (rect.top + rect.bottom - fixedElem.offsetHeight) / 2;
        case "clientbottom":
            return rect.bottom - fixedElem.offsetHeight;
        case "bottom":
        default:
            return rect.bottom;
    };
};


var FixedTips = function(tip, tipoptions) {
    this.Tip = $$$(tip); //提示框

    this._trigger = null; //触发对象
    this._timer = null; //定时器
    this._cssTip = this.Tip.style; //简化代码
    this._onshow = false; //记录当前显示状态

    this.SetOptions(tipoptions);
    //处理Tip对象
    var css = this._cssTip;
    css.margin = 0; //避免定位问题
    css.position = "absolute"; css.visibility = "hidden";
    css.display = "block"; css.zIndex = 99;
    css.left = this._cssTip.top = "-9999px"; //避免占位出现滚动条
    //offset修正参数
    var iLeft = 0, iTop = 0, p = this.Tip;
    while (p.offsetParent) {
        p = p.offsetParent; iLeft += p.offsetLeft; iTop += p.offsetTop;
    };
    this._offsetleft = iLeft;
    this._offsettop = iTop;

    //ie6处理select
    if (isIE6) {
        var iframe = document.createElement("<iframe style='position:absolute;filter:alpha(opacity=0);display:none;'>");
        document.body.insertBefore(iframe, document.body.childNodes[0]);
        this._cssiframe = iframe.style;
    };

    //用于触发方式隐藏
    this._fTH = BindAsEventListener(this, function(e) {

        this.Hide();

    });
};
FixedTips.prototype = {
    //设置默认属性
    SetOptions: function(tipoptions) {
        this.tipoptions = {//默认值
            ShowType: "both", //显示方式
            HideType: "both", //隐藏方式
            ShowDelayType: "touch", //显示延迟方式
            HideDelayType: "touch", //隐藏延迟方式
            //"click":只用点击方式,"touch":只用触发方式,"both":两个都使用,"none":都不使用
            ShowDelay: 300, //显示延时时间
            HideDelay: 300, //隐藏延时时间
            Fixed: { Align: 'clientleft', vAlign: 'top' }, //定位对象
            onShow: function() { }, //显示时执行
            onHide: function() { } //隐藏时执行
        };
        tipExtend(this.tipoptions, tipoptions || {});
    },

    //添加触发对象
    Add: function(elem, mes) {
        var elem = $$$(elem), trigger = tipExtend(tipExtend({ Elem: elem }, this.tipoptions), {});
        this._trigger = trigger;
        //this.Show();
        this.Tip.innerHTML = mes;
        //根据预设定位和自定义定位计算left和top
        var trigger = this._trigger,
		pos = GetRelative(trigger.Elem, this.Tip, trigger.Fixed),
		iLeft = pos.Left, iTop = pos.Top;
        //设置位置并显示
        this._cssTip.left = iLeft - this._offsetleft + "px";
        this._cssTip.top = iTop - this._offsettop + "px";
        this._cssTip.visibility = "visible";
        //ie6处理select
        if (isIE6) {
            var css = this._cssiframe;
            css.width = this.Tip.offsetWidth + "px";
            css.height = this.Tip.offsetHeight + "px";
            css.left = iLeft + "px"; css.top = iTop + "px"; css.display = "";
        };
    },

    Remove: function(elem) {
        this._cssTip.left = '-9999px';
        if (isIE6) {
            var css = this._cssiframe;
            css.left = '-9999px';
        }
    }
};

var inputTips = {};
inputTips.tip = null;
inputTips.show = function(el, mes) {
    if (document.getElementById('inputTips_wrap') == null) {
        var tipDiv = document.createElement('div');
        tipDiv.id = 'inputTips_wrap';
        tipDiv.className = 'tipText';
        document.body.appendChild(tipDiv);
    }
    if (inputTips.tip == null)
        inputTips.tip = new FixedTips('inputTips_wrap');

    inputTips.tip.Add(el, mes);
}
inputTips.hide = function(el) {
    inputTips.tip.Remove(el);
}

//Cookie读写
function readCookie(name) {
    var start = document.cookie.indexOf(name);
    var end = document.cookie.indexOf(";", start);
    return start == -1 ? null : unescape(document.cookie.substring(start + name.length + 1, (end > start ? end : document.cookie.length)));
}

function createCookie(name, value) {
    expires = new Date();
    expires.setTime(expires.getTime() + (86400 * 365));
    document.cookie = name + "=" + escape(value) + "; expires=" + expires.toGMTString() + "; path=/";
}

//桌面面板Ajax请求
var panelHelper = {};
panelHelper.byhand = function(el, url, delay) {
    $('#' + el).html('<div class="part"><div class="loadingContent"><img src="/images/iframe_loading.gif" alt="数据加载中"/></div></div>');
    panelHelper.init(el, url, delay);
}
panelHelper.init = function(el, url, delay) {
    panelHelper.getHtml(el, url, delay);
    window.setInterval(function() {
        panelHelper.getHtml(el, url, delay);
    }, delay * 1000);
}
panelHelper.getHtml = function(el, url, delay) {
    $.ajax({
        url: url,
        type: 'GET',
        dataType: 'html',
        success: function(msg) {
            $('#' + el).html(msg);
        },
        error: function() {
            $('#' + el).html('<div class="part"><div class="loadingContent">可能由于网络原因，请求数据失败，<br />请点击[<a href="javascript:panelHelper.byhand(\'' + el + '\',\'' + url + '\',\'' + delay + '\')"><strong>这里</strong></a>]重新请求。</div></div>');
        }
    });
}

function disableBackspace() {
    document.onkeydown = function() { if (event.keyCode == 8) return false; };  //屏闭退格健
    $('input,textarea').keydown(function() { window.event.cancelBubble = true; });
}

function dhmCalculate(gid, hideId) {
    var m = 0;
    if (!isNaN(parseInt($('#d_' + gid).val())))
        m += parseInt($('#d_' + gid).val()) * 24 * 60;
    m += parseInt($('#h_' + gid + ' :selected').val()) * 60;
    m += parseInt($('#m_' + gid + ' :selected').val());
    $('#' + hideId).val(m);
}